<template>
  <el-card>
    <!-- 模式切换按钮 -->
    <div class="view-mode-toggle">
      <div class="sort" v-if="viewMode === 'thumbnail'">
        <div class="flex alc" v-for="(item, index) in sortOptions" :key="index">
          <span>{{ item }}</span>
          <!-- 升序图标 -->
          <el-icon
            @click="sort(index, 'asc', item)"
            :class="{ active: sortStates[index] === 'asc' }"
          >
            <SortUp />
          </el-icon>
          <!-- 降序图标 -->
          <el-icon
            style="margin-left: -8px"
            @click="sort(index, 'desc', item)"
            :class="{ active: sortStates[index] === 'desc' }"
          >
            <SortDown />
          </el-icon>
        </div>
      </div>
      <el-radio-group v-model="viewMode" size="small">
        <el-radio-button :value="'list'">列表模式</el-radio-button>
        <el-radio-button :value="'thumbnail'">缩略图模式</el-radio-button>
      </el-radio-group>
    </div>
    <!-- 缩略图模式 -->
    <div v-if="viewMode === 'thumbnail'" class="thumbnail-grid">
      <div
        v-for="item in tableConfig.list"
        :key="item"
        class="thumbnail-item"
        @click="handleAction('edit', item)"
      >
        <div class="thumbnail-img-box">
          <img :src="item.cover_img" alt="图片" class="thumbnail-img" />
        </div>
        <p></p>
        <span :title="item.name" class="thumbnail-title">{{ item.name }}</span>
      </div>
    </div>
    <div>
      <!-- 列表模式 -->
      <el-table
        :data="tableConfig.list"
        style="width: 100%"
        v-if="viewMode === 'list'"
        @sort-change="handleSortChange"
      >
        <!-- 动态生成表格列 -->
        <el-table-column
          v-for="column in tableConfig.columns"
          :key="column.prop"
          :prop="column.prop"
          :label="column.label"
          :sortable="column.sortable ? 'custom' : false"
          :fixed="column.fixed"
          :width="column.width || 'auto'"
        >
          <!-- 自定义列内容 - 图片类型 -->
          <template v-if="column.type === 'image'" #default="scope">
            <img
              :src="scope.row[column.prop]"
              alt="封面"
              class="tableImg"
              @click="handleAction('edit', scope.row)"
            />
          </template>

          <!-- 自定义列内容 - 名称类型 -->
          <template v-else-if="column.type === 'name'" #default="scope">
            <div @click="handleAction('edit', scope.row)" class="tableName">
              {{ scope.row[column.prop] }}
            </div>
          </template>

          <!-- 自定义列内容 - 操作按钮类型 -->
          <template v-else-if="column.type === 'actions'" #default="scope">
            <div class="action-wrapper" style="display: flex">
              <template v-for="action in column.actions" :key="action.label">
                <div
                  v-if="
                    action.type === 'edit' ||
                    action.pageType === 'resourceDownload'
                  "
                >
                  <el-tooltip
                    class="box-item"
                    effect="dark"
                    :content="action.label"
                    placement="top"
                  >
                    <el-icon
                      @click="
                        handleAction(action.type, scope.row, action.pageType)
                      "
                      class="action-icon"
                    >
                      <component :is="getIcon(action.type)" />
                    </el-icon>
                  </el-tooltip>
                </div>

                <div
                  v-else-if="
                    action.type === 'down' &&
                    action.pageType !== 'resourceDownload'
                  "
                >
                  <el-popover placement="bottom" width="100" trigger="click">
                    <template #reference>
                      <el-icon class="action-icon" :class="action.type">
                        <component :is="getIcon(action.type)" />
                      </el-icon>
                    </template>

                    <!-- 弹出的内容 -->
                    <div class="action-btn">
                      <a @click="downItem(scope.row, 'original')">下载原图</a>
                      <a @click="downItem(scope.row, 'img')">下载图片</a>
                    </div>
                  </el-popover>
                </div>
              </template>
            </div>
          </template>

          <!-- 默认显示内容 -->
          <template v-else #default="scope">
            {{ scope.row[column.prop] }}
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页部分 -->
      <el-pagination
        v-model:currentPage="tableConfig.page"
        layout="total, prev, pager, next, jumper"
        v-if="tableConfig.total"
        style="justify-content: end"
        :total="tableConfig.total"
        :page-size="tableConfig.pageSize"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </el-card>
</template>

<script setup>
import { ref } from 'vue';
import { EditPen, Download, View } from '@element-plus/icons-vue';
import { isCompressedFile } from '@/utils';
// 接收父组件的值
const { tableConfig } = defineProps({
  tableConfig: {
    type: Object,
    default: () => ({
      total: 0,
      page: 1,
      pageSize: 10,
      list: [],
      columns: [],
    }),
  },
});

// 定义 emit
const emit = defineEmits([
  'editItem',
  'sortBy',
  'sizeChange',
  'currentChange',
  'sortList',
  'actionDialog',
  'downFile',
]);
// 默认显示缩略图模式
const viewMode = ref('thumbnail');
// 排序项 "上架时间" 和 "下载次数"
const sortOptions = ['上架时间', '下载次数'];
// 存储每个排序项的排序状态（默认都无排序状态）
const sortStates = ref(Array(sortOptions.length).fill(null));
// 默认排序状态
const sortType = ref('asc');
// 排序计数点击第三下取消选中
const sortNum = ref(0);
// 排序函数
const sort = (index, item) => {
  sortNum.value += 1;
  sortType.value = sortType.value == 'asc' ? 'desc' : 'asc';
  // 重置所有排序状态
  sortStates.value = Array(sortOptions.length).fill(null);
  if (sortNum.value > 2) {
    sortNum.value = 0;
    sortType.value = '';
  }
  // 设置当前点击项的排序类型
  sortStates.value[index] = sortType.value;
  emit('sortBy', sortType.value, item);
};
// 处理试图变化
const handleSortChange = ({ prop, order }) => {
  emit('sortList', { prop, order });
};
// 处理页码切换
const handleSizeChange = (val) => {
  emit('sizeChange', val);
};
// 处理页码切换
const handleCurrentChange = (val) => {
  emit('currentChange', val);
};
// 图标组件
const getIcon = (type) => {
  const iconMap = {
    edit: EditPen,
    down: Download,
    view: View,
  };
  return iconMap[type] || EditPen; // 默认返回 EditPen 图标
};
// 操作函数映射表
const actionMap = {
  edit: (row) => editItem(row),
  down: (row) => downItem(row),
};
// 图标点击事件
const handleAction = (type, row, pageType = '') => {
  const isComp = isCompressedFile(row.file);
  if (row.fileType == 'pdf') return window.open(row.file, '_blank');
  if ((pageType == 'resourceDownload' && type == 'down') || isComp) {
    emit('downFile', {
      file: row.file,
      name: row.name,
      id: row.id,
    });
    return;
  }
  const action = actionMap[type]; // 根据 type 获取对应的函数
  if (action) {
    action(row); // 调用相应的操作函数
  } else {
  }
  emit('actionDialog', { ...row, type });
};

// 编辑
const editItem = (row) => {
  emit('editItem', row);
};
// 下载
const downItem = (row, type) => {
  emit('downItem', { ...row, type });
};
</script>
<style lang="scss" scoped>
.view-mode-toggle {
  display: flex;
  justify-content: end;
  margin-bottom: 34px;

  .sort {
    display: flex;
    align-items: center;

    .alc {
      align-items: center;
      cursor: pointer;
      margin-right: 4px;
      color: #86909c;
      font-size: 14px;

      .el-icon {
        transform: scaleX(-1);

        &.active {
          color: #1c5dff;
        }
      }
    }
  }
}

.thumbnail-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 24px;
  // justify-content: space-between;
}

.thumbnail-item {
  width: calc(16.66667% - 24px);
  border-radius: 4px;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  transition: all 0.2s;
  cursor: pointer;

  &:hover .thumbnail-img-box:after {
    opacity: 1;
  }

  &:nth-child(n + 7) {
    margin-top: 16px;
  }

  &:hover .thumbnail-title {
    color: #165dff;
  }

  .thumbnail-img-box {
    width: 100%;
    height: 0;
    border-radius: 8px;
    padding-top: 56.25%;
    background: #f7f8fa;
    overflow: hidden;
    box-sizing: border-box;
    position: relative;

    .thumbnail-img {
      border-radius: 4px;
      width: 100%;
      height: 100%;
      position: absolute;
      left: 0;
      top: 50%;
      -webkit-transform: translateY(-50%);
      transform: translateY(-50%);
    }

    &::after {
      content: '';
      position: absolute;
      left: 0;
      top: 0;
      width: 100%;
      height: 100%;
      background: rgba(0, 0, 0, 0.3);
      -webkit-transition: opacity 0.3s;
      transition: opacity 0.3s;
      opacity: 0;
    }
  }

  .thumbnail-title {
    margin-top: 14px;
    font-size: 14px;
    line-height: 16px;
    padding: 0 0.521vw;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    color: #1d2129;
    text-align: center;
  }
}

.tableImg {
  width: 140px;
  height: auto;
  // object-fit: cover;
  border-radius: 4px;
  cursor: pointer;
}

.tableName {
  cursor: pointer;

  &:hover {
    color: #1c5dff;
    text-decoration: underline;
    text-underline-offset: 3px;
    /* 控制下划线和文字的距离 */
  }
}

:deep(.el-card__body) {
  padding: 40px !important;
}

.action-btn {
  display: flex;
  flex-direction: column;

  a:hover {
    opacity: 0.6;
  }
}
.action-icon {
  font-size: 20px;
  cursor: pointer;

  &:first-child {
    margin-left: 5px;
    color: rgb(22, 93, 255);
    margin-right: 20px;
  }
}
.down {
  color: rgb(29, 33, 41) !important;
}
</style>
